//
//  AppServiceInterface.m
//  EastMarket
//
//  Created by 李鹏程 on 16/10/20.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "AppServiceInterface.h"

//static NSString *HttpBaseURL = @"http://tm.donglinjishi.com/api";
static NSString *HttpBaseURL = @"http://m.donglin.me/api";


@implementation AppServiceInterface

+(NSString *)callServerInterfaceReturnByString:(NSString *)url params:(NSMutableDictionary *) paramDict
{
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    NSLog(@"url:%@ paramDict: %@",url, paramDict);
    __block id resultEnd = nil;
    /**
     同步请求可以参考manager post里，即手工创建AFHTTPRequestOperation，设置requestSerializer和responseSerializer
     然后start再wait，这里因为设计到https证书，直接创建出来的AFHTTPRequestOperation.securityPolicy设置后不起作用，所以还是用manager
     通过manager post后，得到manager创建的AFHTTPRequestOperation来wait等待结束，不过异步过程中的出错信息拿不到
     */
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager setSecurityPolicy:[self customSecurityPolicy]];

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"application/x-json",@"text/html", @"text/plain", nil];
    
    // 网络访问是异步的,回调是主线程的,因此程序员不用管在主线程更新UI的事情
    [manager POST:url parameters:paramDict progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
        for (NSHTTPCookie *tempCookie in cookies) {
            //打印获得的cookie
            debugLog(@"getCookie: %@", tempCookie);
        }

        NSStringEncoding gbEncoding = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        //先用utf-8解析
        NSString *result  = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        if (result == NULL) {
            //解析不到，改用gb2312
            result  = [[NSString alloc] initWithData:responseObject encoding:gbEncoding];
        }
        resultEnd = result;
        dispatch_semaphore_signal(semaphore);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        debugLog(@"%@", error);
    }];
    NSTimeInterval timeout = 20; //超时时间
    dispatch_semaphore_wait(semaphore, dispatch_time(DISPATCH_TIME_NOW, timeout * NSEC_PER_SEC));
    return resultEnd;
}

+(NSDictionary *)parseStringToJson:(NSString*)sourceStr
{
    NSDictionary *resultDict;
    if ([GlobalUnit isBlankString:sourceStr]) {
        resultDict = [NSDictionary dictionaryWithObjectsAndKeys:@"-99",@"errCode",@"网络异常，获取数据失败!", @"errMsg" ,nil];
    }
    else
    {
        /**
         options:
         NSJSONReadingMutableContainers：返回可变容器，NSMutableDictionary或NSMutableArray。
         NSJSONReadingMutableLeaves：返回的JSON对象中字符串的值为NSMutableString，目前在iOS 7上测试不好用，应该是个bug，参见：
         http://stackoverflow.com/questions/19345864/nsjsonreadingmutableleaves-option-is-not-working
         NSJSONReadingAllowFragments：允许JSON字符串最外层既不是NSArray也不是NSDictionary，但必须是有效的JSON Fragment。例如使用这个选项可以解析 @“123” 这样的字符串。参见：
         http://stackoverflow.com/questions/16961025/nsjsonserialization-nsjsonreadingallowfragments-reading
         */
        NSError *error;
        resultDict = [NSJSONSerialization JSONObjectWithData:[sourceStr dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&error];
        if (resultDict == nil) {
            debugLog(@"json parse failed \r\n");
            resultDict = [NSDictionary dictionaryWithObjectsAndKeys:@"-98",@"errCode",@"Data parsing error！",@"errMsg", nil];
        }
    }
    return resultDict;
}

+(NSDictionary *)callServerInterface:(NSString *)url params:(NSMutableDictionary *) paramDict
{
    NSDictionary *resultDict;
    resultDict = [self parseStringToJson:[self callServerInterfaceReturnByString:url params:paramDict]];
    debugLog(@"接口%@\n参数%@\n返回%@",url,paramDict,resultDict);
    return resultDict;
}

// 允许不安全证书的设置
+ (AFSecurityPolicy*)customSecurityPolicy
{
    /**** SSL Pinning ****/
    AFSecurityPolicy *securityPolicy = [[AFSecurityPolicy alloc] init];
    [securityPolicy setAllowInvalidCertificates:YES];
    /**** SSL Pinning ****/
    return securityPolicy;
}

// .手机验证码登录
+(NSDictionary *)LoginByMobileCheckCode:(NSString *) mobile mobileCheckCode:(NSString *)mobileCheckCode channel:(NSInteger)channel{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:mobile forKey:@"mobile"];
    [params setObject:mobileCheckCode forKey:@"mobileCheckCode"];
    [params setObject:[NSNumber numberWithInteger:channel] forKey:@"channel"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@accountapi/LoginByMobileCheckCode", HttpBaseURL] params:params];
}

// .注销
+(NSDictionary *)Logout {
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@accountapi/Logout", HttpBaseURL] params:nil];
}

// 003.登录
+(NSDictionary *)Login:(NSString *)mobile password:(NSString *)password {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:mobile forKey:@"phone"];
    [params setObject:password forKey:@"password"];
    //    [params setObject:channel forKey:@"channel"];
    
    NSDictionary *dic;
    dic = [self callServerInterface:[NSString stringWithFormat:@"%@/login", HttpBaseURL] params:params];
    NSLog(@"userInfo:%@",dic);
    if (dic && [GlobalUnit getIntValue:[dic objectForKey:@"success"]]==0) {
        if (!globalManager.isLogined && ![GlobalUnit isBlankString:[GlobalUnit getStringValue:[dic objectForKey:@"message"]]]) {
            [GlobalUnit showAlertHint:@"提示信息" message:[GlobalUnit getStringValue:[dic objectForKey:@"message"]]];
        }
        globalManager.isLogined = true;
    }
    return dic;
}

// 004.手机验证码
+(NSDictionary *)SendMobileCheckCode:(NSString *)mobile {
    
    //    MobileCheckCodeTypeEnum
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:mobile forKey:@"phone"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/sms/verification/%@", HttpBaseURL, mobile] params:params];
}

// 005.注册
+(NSDictionary *)Register:(NSString *)phone password:(NSString *)password verifyCode:(NSString *)verifyCode invitationCode:(NSString *)invitationCode {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:phone forKey:@"phone"];
    [params setObject:password forKey:@"password"];
    [params setObject:verifyCode forKey:@"verifyCode"];
    [params setObject:invitationCode forKey:@"invitationCode"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/register", HttpBaseURL] params:params];
}

// 006.当前用户信息
+(NSDictionary *)GetCurrentAccountInfo {
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/user/get", HttpBaseURL] params:nil];
}

// 007.更新用户信息
+(NSDictionary *)updateCurrentAccountInfo:(NSString *)shopName contactName:(NSString *)contactName shopAddress:(NSString *)shopAddress consignee:(NSString *)consignee region:(NSString *)region {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:shopName forKey:@"shopName"];
    [params setObject:contactName forKey:@"contactName"];
    [params setObject:shopAddress forKey:@"shopAddress"];
    [params setObject:consignee forKey:@"consignee"];
    [params setObject:region forKey:@"region"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/user/update", HttpBaseURL] params:params];
}

// 008.商品搜索
+(NSDictionary *)productOfSearch:(NSString *)name productCatePath:(NSString *)productCatePath order:(NSString *)order page:(NSInteger)page pageSize:(NSInteger)pageSize{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:name forKey:@"name"];
    [params setObject:productCatePath forKey:@"productCatePath"];
    [params setObject:order forKey:@"order"];
    [params setObject:[NSNumber numberWithInteger:page] forKey:@"page"];
    [params setObject:[NSNumber numberWithInteger:pageSize] forKey:@"pageSize"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/item/search", HttpBaseURL] params:params];
}

// 009.类目数
+(NSDictionary *)getProductCate {

    return [self callServerInterface:[NSString stringWithFormat:@"%@/productCate/list", HttpBaseURL] params:nil];
}

// 010.购物车页面
+(NSDictionary *)getCartProducts {

    return [self callServerInterface:[NSString stringWithFormat:@"%@/cart", HttpBaseURL] params:nil];
}

// 011. 购物车商品新增接口
/**
 地址：/api/cartItem
 参数：
 itemId  商品id
 num 数量
 */
+(NSDictionary *)cartItem:(NSString *)itemId itemNum:(NSInteger)itemNum {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:itemId forKey:@"itemId"];
    [params setObject:[NSNumber numberWithInteger:itemNum] forKey:@"num"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/cartItem", HttpBaseURL] params:params];
}

#pragma mark -- 有关订单接口
// 012. 订单创建页面接口
/**
 POST：
 http://localhost:8080/api/order/create/page
 参数：
 itemIdList  多个itemid 用 逗号隔开 如  itemIdList=123,456
 numList  对应itemId的数量，多个用逗号隔开 如 numList=12,34
 */
+(NSDictionary *)OrderCreatePage:(NSString *)itemIdList numList:(NSString *)numList {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:itemIdList forKey:@"itemIdList"];
    [params setObject:numList forKey:@"numList"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/order/create/page", HttpBaseURL] params:params];
}

// 013. 订单创建接口
/**
 地址：
 /api/order/create
 参数：
 data  json字符串，格式为：
 {  "itemInfoList": [ //商品信息
 {  "itemId": "32151",  //商品id  "num": "2"  //商品数量  }
 ],   "orderInfoList": [ //订单信息
 {  "sellerId": "18",  //供应商id  "payType": "ONLINE",  //支付方式  "expectedDeliveryTime": "2016-11-01" //期望送货日期   }
 ]
 }
 */
+(NSDictionary *)OrderCreate:(NSString *)data {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:data forKey:@"data"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/order/create", HttpBaseURL] params:params];
}

// 014. 订单列表界面
/**
 地址：/api/ucenter/orderList
 参数：
 status  订单状态 可选值：WAIT_PAY  WAIT_VERIFY  VERIFIED  WAIT_CANCEL,CANCELED
 */
+(NSDictionary *)orderList:(NSString *)status page:(NSInteger)page pageSize:(NSInteger)pageSize{

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:status forKey:@"status"];
    [params setObject:[NSNumber numberWithInteger:page] forKey:@"page"];
    [params setObject:[NSNumber numberWithInteger:pageSize] forKey:@"pageSize"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/ucenter/orderList", HttpBaseURL] params:params];
}

// 015. 订单详情api接口
/**
 文档正文
 地址：/api/order/get
 参数：
 id 订单id
 */
+(NSDictionary *)orderDetail:(NSString *)orderId {
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:orderId forKey:@"id"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/order/get", HttpBaseURL] params:params];
}

// 016. 删除订单接口
/**
 文档正文
 地址： /api/order/del
 参数：
 id
 */
+(NSDictionary *)orderDelete:(NSString *)orderId {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:orderId forKey:@"id"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/order/del", HttpBaseURL] params:params];
}

// 017. 取消订单接口
/**
 文档正文
 地址： /api/order/cancel
 参数：
 id
 */
+(NSDictionary *)orderCancle:(NSString *)orderId {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:orderId forKey:@"id"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/order/cancel", HttpBaseURL] params:params];
}

// 18 首页接口
/**
 文档正文
 /api/index
 */
+(NSDictionary *)GetIndexPage {

    return [self callServerInterface:[NSString stringWithFormat:@"%@/index", HttpBaseURL] params:nil];
}

// 19 找回密码接口
/**
 文档正文
 /api/forgetPwd
 参数：
 phone 手机号
 verifyCode 手机验证码
 password 新密码
 返回code的
 -1 信息输入不完整
 -2 验证码错误
 -3 用户不存在
 */
// .找回密码
+(NSDictionary *)ForgetPassword:(NSString *)mobile password:(NSString *)password mobileCheckCode:(NSString *)mobileCheckCode{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:mobile forKey:@"phone"];
    [params setObject:password forKey:@"password"];
    [params setObject:mobileCheckCode forKey:@"verifyCode"];
    //    [params setObject:channel forKey:@"channel"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/forgetPwd", HttpBaseURL] params:params];
}

// 20 修改密码接口
/**
 文档正文
 地址：/api/modifyPwd
 参数：
 originalPassword  原密码
 password 新密码
 返回code：
 -1 原密码不正确
 */
+(NSDictionary *)ModifyPassword:(NSString *)originalPassword password:(NSString *)password {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:originalPassword forKey:@"originalPassword"];
    [params setObject:password forKey:@"password"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/modifyPwd", HttpBaseURL] params:params];
}

//21 供应商列表api
/**
 
 文档正文
 /api/seller/list
 */
+(NSDictionary *)GetSellerList {

    return [self callServerInterface:[NSString stringWithFormat:@"%@/seller/list", HttpBaseURL] params:nil];
}

//22 添加供应商接口
/**
 文档正文
 /api/seller/addCustomer
 参数：
 invitationCode   邀请码
 */
+(NSDictionary *)AddCustomer:(NSString *)invitationCode {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:invitationCode forKey:@"invitationCode"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/seller/addCustomer", HttpBaseURL] params:params];
}

//23 供应商信息获取接口
/**
 文档正文
 /api/seller/get
 
 参数： id  供应商id
 */
+(NSDictionary *)GetSellerInfo:(NSString *)sellerId {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:sellerId forKey:@"id"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/seller/get", HttpBaseURL] params:params];
}
+(NSDictionary *)productOfSearchWithSeller:(NSString *)name productCatePath:(NSString *)productCatePath order:(NSString *)order page:(NSInteger)page pageSize:(NSInteger)pageSize sellerId:(NSString *)sellerId; {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:name forKey:@"name"];
    [params setObject:productCatePath forKey:@"productCatePath"];
    [params setObject:order forKey:@"order"];
    [params setObject:[NSNumber numberWithInteger:page] forKey:@"page"];
    [params setObject:[NSNumber numberWithInteger:pageSize] forKey:@"pageSize"];
    [params setObject:sellerId forKey:@"sellerId"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/item/search", HttpBaseURL] params:params];
}

// 24 常用料查询接口
/**
 文档正文
 /api/customerItem/list
 参数：
 productCatePath 类目路径
 page 页数
 pageSize
 */
+(NSDictionary *)GetCustomerList:(NSString *)productCatePath page:(NSInteger)page pageSize:(NSInteger)pageSize {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:productCatePath forKey:@"productCatePath"];
    [params setObject:[NSNumber numberWithInteger:page] forKey:@"page"];
    [params setObject:[NSNumber numberWithInteger:pageSize] forKey:@"pageSize"];
    
    return [self callServerInterface:[NSString stringWithFormat:@"%@/customerItem/list", HttpBaseURL] params:params];
}

// 25 常用料新增接口
/**
 文档正文
 /api/customerItem/add
 参数：
 itemId
 */
+(NSDictionary *)CustomerItemAdd:(NSString *)itemId {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:itemId forKey:@"itemId"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/customerItem/add", HttpBaseURL] params:params];
}

// 26 常用料删除接口
/**
 文档正文
 /api/customerItem/del
 参数
 1. itemId
 */
+(NSDictionary *)CustomerItemDelete:(NSString *)itemId {

    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:itemId forKey:@"itemId"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/customerItem/del", HttpBaseURL] params:params];
}

// 购物车中item选中
+(NSDictionary *)CartItemCheck:(NSString *)checkedIds {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:checkedIds forKey:@"checkedIds"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/cartItem/check", HttpBaseURL] params:params];
}

// 购物车中item取消
+(NSDictionary *)CartItemUnCheck:(NSString *)checkedIds {
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setObject:checkedIds forKey:@"uncheckedIds"];
    return [self callServerInterface:[NSString stringWithFormat:@"%@/cartItem/check", HttpBaseURL] params:params];
}

@end
